package com.hakgc.rent.service.impl;


import com.hakgc.rent.dao.DistrictDao;
import com.hakgc.rent.dao.StreetDao;
import com.hakgc.rent.dao.impl.DistrictDaoImpl;
import com.hakgc.rent.dao.impl.StreetDaoImpl;
import com.hakgc.rent.entity.District;
import com.hakgc.rent.entity.Street;
import com.hakgc.rent.service.DistrictService;

import java.util.List;

/**
 * @author Xing.Jiejian
 * @date 2020/10/20
 */
public class DistrictServiceImpl implements DistrictService {
    /**
     * 业务方法经常调用数据库相关操作，所以把需要的数据库操作类定义成成员变量
     */
    private DistrictDao districtDao =  new DistrictDaoImpl();
    private StreetDao streetDao = new StreetDaoImpl();

    @Override
    public List<District> findAllWithStreet() {
        // 获取所有的区县集合
        List<District> districtList = districtDao.findAll();
        // 遍历区县
        for (District district : districtList) {
            //根据区县编号，找到对应的街道集合，并关联
            List<Street> streetList = streetDao.findByDistrictId(district.getId());
            district.setStreetList(streetList);
        }
        // 返回组装到的集合
        return districtList;
    }

    @Override
    public List<District> findAll(boolean isWithStreet) {
        // 获取所有的区县集合
        List<District> districtList = districtDao.findAll();
        // 需要关联街道信息，再执行关联查询
        if (isWithStreet) {
            // 遍历区县
            for (District district : districtList) {
                //根据区县编号，找到对应的街道集合，并关联
                List<Street> streetList = streetDao.findByDistrictId(district.getId());
                district.setStreetList(streetList);
            }
        }
        return districtList;
    }

    @Override
    public boolean addDistrict(District district) {
        return districtDao.save(district);
    }

    @Override
    public boolean deleteById(int id) {
        return districtDao.deleteById(id);
    }

    @Override
    public boolean update(District district) {
        return districtDao.update(district);
    }

    @Override
    public District findById(int id) {
        return districtDao.findById(id);
    }

    @Override
    public List<District> findByPage(int pageNo, int pageSize) {
        return districtDao.findByLimit(null,pageNo,pageSize);
    }

    @Override
    public List<District> findByPage(String likeName, int pageNo, int pageSize) {
        // 根据页码和每页显示数量计算偏移量
        int offset = (pageNo - 1) * pageSize;
        // 如果区县为空，则表示查询所有信息
        if (likeName == null || "".equals(likeName)) {
            return districtDao.findByLimit(offset,pageSize);
        }
        return districtDao.findByLimit(likeName, offset, pageSize);
    }

    @Override
    public int getAllCount() {
        return getAllCount(null);
    }

    @Override
    public int getAllCount(String likeName) {
        if (likeName == null || "".equals(likeName)) {
            return districtDao.getAllCount();
        }
        return districtDao.getAllCount(likeName);
    }
}
